using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MyCustomModules_PostNewMessage : System.Web.UI.Page
{
    string conn = System.Configuration.ConfigurationManager.AppSettings.Get("MSSQLConnectionString");
    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Get status information
            ds = mojoPortal.Data.SqlHelper.ExecuteDataset(
                conn, CommandType.StoredProcedure, "usp_GetMessageForDoc",
                new System.Data.SqlClient.SqlParameter("@DocID", Request.QueryString["DocID"]));

            Session["MessagesPosted"] = ds;

            MyCustomModules_MessageWidget widget;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                widget = (MyCustomModules_MessageWidget)LoadControl("~/MyCustomModules/MessageWidget.ascx");
                widget.strMessageID = dr["MessageID"].ToString();
                if ( Request.QueryString["userid"] != null)
                    widget.strCurrentUser = Request.QueryString["userid"].ToString();
                pnlPostMessage.Controls.Add(widget);
            }

            if (Request.QueryString["userid"] == null)
            {
                btnSaveAndClose.Visible = false;
                btnSaveOnly.Visible = false;
                txtMessage.Visible = false;
            }
        }     
    }

    protected void AddNewStatusClick(object sender, EventArgs e)
    {
        // Add new messages here
        mojoPortal.Data.SqlParameterHelper sph = new mojoPortal.Data.SqlParameterHelper(conn, "usp_InsertNewMessage", CommandType.StoredProcedure, 3);
        sph.DefineSqlParameter("@DocID", SqlDbType.Int, ParameterDirection.Input, Int32.Parse(Request.QueryString["DocID"].ToString()));
        sph.DefineSqlParameter("@PostedBy", SqlDbType.UniqueIdentifier, ParameterDirection.Input, new Guid(Request.QueryString["UserID"]));
        sph.DefineSqlParameter("@Message", SqlDbType.NVarChar,2000, ParameterDirection.Input, txtMessage.Text );

        if (txtMessage.Text != "")
        {
            int result = Convert.ToInt32(sph.ExecuteNonQuery());
            if (result == -1)
            {
                lblMessage.Text = "Error occured";
            }
            else if (result > 0)
            {
                lblMessage.Text = "";
                //Send mail
                SendConfirmationMail();
            }
            else
                lblMessage.Text = "Error occured";
        }

        pnlPostMessage.Controls.Clear();

        if (((Button)sender).Text.ToLower() == "save")
            Response.Redirect(Request.RawUrl);
        else
            RegisterStartupScript("RefreshParent", "<script language='javascript'>closeParent();</script>");

    }

    protected void SendConfirmationMail()
    {
        // FullName - get from docid
        // Send to - get from docid
        // Updated By - httpcontext
        // DocumentName - from docid
        // Stauts Message - from grid
        // StatusComments - from grid
        // StatusDateTime - datetime.now
        // Get NEW URL for link to status page - currentpage ? docid&userID
        // 
        string strTo = String.Empty;
        string strCC = String.Empty;
        string strFilePath = String.Empty;

        MailMerge msg = new MailMerge("NewMessagePosted");
        msg.StatusDateTime = DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");

        System.Data.SqlClient.SqlDataReader dr = mojoPortal.Data.SqlHelper.ExecuteReader
           (conn, CommandType.StoredProcedure, "usp_GetDocumentProperties",
           new System.Data.SqlClient.SqlParameter("@DocID", Request.QueryString["DocID"]));
        if (dr.HasRows)
        {
            dr.Read();
            strFilePath = dr["FilePath"].ToString();
            if (HttpContext.Current.User.IsInRole("Content Administrators") || HttpContext.Current.User.IsInRole("Admins"))
            {
                msg.FullName = dr["DocOwner"].ToString();
                strTo = dr["DocOwnerEmail"].ToString();
            }
            else
            {
                msg.FullName = "Admin";
                strTo =  System.Configuration.ConfigurationManager.AppSettings.Get("SMTPTo");
            }
        }
        dr.Close();

        System.Data.SqlClient.SqlDataReader drUser = mojoPortal.Data.SqlHelper.ExecuteReader
           (conn, CommandType.StoredProcedure, "usp_GetUserDetails",
           new System.Data.SqlClient.SqlParameter("@UserEmail", HttpContext.Current.User.Identity.Name.ToString()));
        if (drUser.HasRows)
        {
            drUser.Read();
            msg.UpdatedBy = drUser["name"].ToString();
            msg.DocumentPath = strFilePath;
            msg.DocumentName = Common.GetActualFileName(strFilePath);
            msg.StatusMessage = txtMessage.Text;
            msg.CustomURL = System.Configuration.ConfigurationManager.AppSettings.Get("URLSpecifiedInMail") + "/" +
                System.Configuration.ConfigurationManager.AppSettings.Get("ShowPostMessageLink") +
                "?DocID=" + Request.QueryString["DocID"] + "&fromMail=yes";
        
        }
        drUser.Close();

        msg.GetMailDetails();
        Common.SendMailMessage(strTo, "", "", msg.Subject, msg.Body);
        //MailHelper.SendMailMessage(strTo, "", "", msg);
    }

    
}
